package com.aspirecn.auth.service;

import com.aspirecn.auth.domain.SysUser;
import com.aspirecn.auth.repository.SysUserRepository;
import com.aspirecn.auth.web.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Optional;
import java.util.Set;

@Service("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService {
	private static final Logger LOG = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private SysUserRepository sysUserRepository;

	private final AccountStatusUserDetailsChecker detailsChecker = new AccountStatusUserDetailsChecker();


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		LOG.info("test4444444444444444");
		String lowcaseUsername = username.toLowerCase();
		Optional<SysUser> realUser = sysUserRepository.findOneWithRolesByUsername(lowcaseUsername);
		
		return realUser.map(user -> {
			Set<GrantedAuthority> grantedAuthorities = user.getAuthorities();
			
			User userDetails = new User(user.getUsername(), 
					user.getPassword(),
					user.isEnabled(),
					true,
					true,
					true,
					grantedAuthorities);
			
			detailsChecker.check(userDetails);
			return userDetails;
			
		}).orElseThrow(() -> new UsernameNotFoundException("用户" + lowcaseUsername + "不存在!"));
	}
}
